package net;

import gui.client.ClientControlFrame;

import java.awt.Point;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;

import net.dto.ClientObject;
import net.dto.ServerObject;
import net.protocols.ClientProtocol;

public class Client {

	public int id;
	
	public static void main(String[] args){
		new Client();
	}
	
	private ObjectOutputStream out;
	private ObjectInputStream in;
	private Socket client;
	private ClientProtocol prot;
	
	public Client(){
		try {
			
			client = new Socket("localhost",8889);
			out = new ObjectOutputStream(client.getOutputStream());
			in = new ObjectInputStream(client.getInputStream());
			prot = new ClientProtocol(this);
			initializeListening();
			
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void initializeListening() {
		ServerObject fromServer;
		ClientObject fromUser;
		
		try {
			while ((fromServer = (ServerObject) in.readObject()) != null) {
				print("#Server# "+fromServer);
				  fromUser = prot.processInput(fromServer);
				if(fromUser != null){
					print("Client "+id+" > "+fromUser);
					out.writeObject(fromUser);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	private void close(){
		try {
			out.close();
			in.close();
			client.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void print(String message){
		System.out.println(message);
	}
}
